package com.kj.mynote.Activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.kj.mynote.Bean.NoteBean;
import com.kj.mynote.Bean.NoteDeptBean;
import com.kj.mynote.R;
import com.kj.mynote.Util.AutoUtils;
import com.kj.mynote.Util.ExcelUtils;
import com.kj.mynote.Util.FileUtils;
import com.kj.mynote.Util.ToolUtils;

import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindMultiCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jxl.biff.drawing.Chart;

public class MainActivity extends BaseActivity {
    private RelativeLayout rlStime, rlEtime;
    private TextView tvClass, tvStime, tvEtime;
    private FloatingActionButton btnAdd, btnExport;
    private ListView lv;
    private ListView lvGroup;
    List<NoteBean> list = new ArrayList<NoteBean>();
    List<NoteBean> exportList;
    List<NoteDeptBean> data = new ArrayList<NoteDeptBean>();
    NoteListAdapter adapter;
    GroupListAdapter adapterGroup;
    PopupWindow pwClass;
    int page = 0, limit = 8;
    private int lastVisibleItem;// 最后一个可见项
    private int totalItems;// 所有项
    private boolean isLoading = false;

    private final static int sCode = 1;
    private final static int eCode = 2;

    private long sDate = 0;
    private long eDate = 0;
    private String dept = "全部分组";
    RelativeLayout loading;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);
        AutoUtils.setSize(this, true, 750, 1334);
        AutoUtils.auto(this);
        initFile();
        init();
        Linstener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            clearSearch();
            searchNote(true);
            searchDept();
            if (adapterGroup != null) {
                adapterGroup.notifyDataSetChanged();
            }
        }
        if (requestCode == sCode) {
            if (data == null) {
                return;
            }
            sDate = data.getLongExtra("date", 0);
            if (sDate == 0) {
                tvStime.setText("开始时间");
            } else {
                String d = ToolUtils.TS2S(sDate, "yyyy-MM-dd");
                tvStime.setText(d);
            }
            searchNote(true);

        }
        if (requestCode == eCode) {
            if (data == null) {
                return;
            }
            eDate = data.getLongExtra("date", 0);
            if (eDate == 0) {
                tvEtime.setText("结束时间");
            } else {
                String d = ToolUtils.TS2S(eDate, "yyyy-MM-dd");
                tvEtime.setText(d);
            }
            searchNote(true);
        }
    }

    private void init() {
        loading = (RelativeLayout) findViewById(R.id.note_main_rl_loading);
        btnAdd = (FloatingActionButton) findViewById(R.id.note_main_btn_add);
        btnExport = (FloatingActionButton) findViewById(R.id.note_main_btn_export);
        tvClass = (TextView) findViewById(R.id.note_main_tv_dept);
        tvStime = (TextView) findViewById(R.id.note_main_tv_stime);
        tvEtime = (TextView) findViewById(R.id.note_main_tv_etime);
        rlStime = (RelativeLayout) findViewById(R.id.note_main_rl_stime);
        rlEtime = (RelativeLayout) findViewById(R.id.note_main_rl_etime);
        lv = (ListView) findViewById(R.id.note_main_list);
        adapter = new NoteListAdapter();
        lv.setAdapter(adapter);
        searchDept();
        searchNote(true);
    }

    private void Linstener() {
        loading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                return;
            }
        });
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NoteEditActivity.class);
                startActivityForResult(intent, 0x01);
            }
        });
        btnExport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loading.setVisibility(View.VISIBLE);
                searchNoteForExport();
            }
        });
        tvClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopu();
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, NoteReadActivity.class);
                intent.putExtra("id", list.get(position).getId());
                startActivity(intent);
            }
        });
        rlStime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intnet = new Intent(MainActivity.this, DateSelectActivity.class);
                intnet.putExtra("code", sCode);
                intnet.putExtra("sDate", sDate);
                intnet.putExtra("eDate", eDate);
                startActivityForResult(intnet, sCode);
            }
        });
        rlEtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intnet = new Intent(MainActivity.this, DateSelectActivity.class);
                intnet.putExtra("code", eCode);
                intnet.putExtra("sDate", sDate);
                intnet.putExtra("eDate", eDate);
                startActivityForResult(intnet, eCode);
            }
        });
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (lastVisibleItem == totalItems && scrollState == SCROLL_STATE_IDLE) {
                    if (!isLoading) {// 判断不是正在加载！
                        isLoading = true;
                        page++;
                        searchNote(false);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastVisibleItem = firstVisibleItem + visibleItemCount;
                totalItems = totalItemCount;
            }
        });
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showFCDialog(position);
                return true;
            }
        });
    }

    private void clearSearch() {
        page = 0;
        sDate = 0;
        eDate = 0;
        dept = "全部分组";
        tvStime.setText("开始时间");
        tvEtime.setText("结束时间");
        tvClass.setText(dept);
    }

    private void searchNote(boolean isReflash) {
        if (isReflash) {
            page = 0;
            list.clear();
        }
        StringBuffer sb = new StringBuffer();
        sb.append("select * from notebean where ");
        if (!"全部分组".equals(dept)) {
            sb.append("noteClass = '" + dept + "' and ");
        }
        if (sDate != 0) {
            sb.append("startTime > " + sDate + " and ");
        }
        if (eDate != 0) {
            sb.append("endTime < " + ToolUtils.TSADD(eDate, 1) + " and ");
        }
        Log.e("date", ToolUtils.TS2S(sDate, "yyyy-MM-dd HH:mm:ss"));
        sb.append("1=1 order by id limit " + limit + " offset " + page * limit);
        Cursor cursor = DataSupport.findBySQL(sb.toString());
        while (cursor.moveToNext()) {
            NoteBean bean = new NoteBean();
            bean.setId(cursor.getInt(cursor.getColumnIndex("id")));
            bean.setTitle(cursor.getString(cursor.getColumnIndex("title")));
            bean.setNum(cursor.getInt(cursor.getColumnIndex("num")));
            bean.setFilePath(cursor.getString(cursor.getColumnIndex("filepath")));
            bean.setStartTime(cursor.getLong(cursor.getColumnIndex("starttime")));
            bean.setEndTime(cursor.getLong(cursor.getColumnIndex("endtime")));
            bean.setNoteClass(cursor.getString(cursor.getColumnIndex("noteclass")));
            list.add(bean);
        }
        isLoading = false;
        adapter.notifyDataSetChanged();
    }

    private void searchNoteForExport() {
        exportList = new ArrayList<NoteBean>();
        StringBuffer sb = new StringBuffer();
        sb.append("select * from notebean where ");
        if (!"全部分组".equals(dept)) {
            sb.append("noteClass = '" + dept + "' and ");
        }
        if (sDate != 0) {
            sb.append("startTime > " + sDate + " and ");
        }
        if (eDate != 0) {
            sb.append("endTime < " + ToolUtils.TSADD(eDate, 1) + " and ");
        }
        sb.append("1=1 order by id ");
        new searchAll().execute(sb.toString());
    }

    class searchAll extends AsyncTask<String, String, Cursor> {

        @Override
        protected Cursor doInBackground(String... params) {
            return DataSupport.findBySQL(params[0]);
        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            super.onPostExecute(cursor);
            while (cursor.moveToNext()) {
                NoteBean bean = new NoteBean();
                bean.setId(cursor.getInt(cursor.getColumnIndex("id")));
                bean.setTitle(cursor.getString(cursor.getColumnIndex("title")));
                bean.setNum(cursor.getInt(cursor.getColumnIndex("num")));
                bean.setFilePath(cursor.getString(cursor.getColumnIndex("filepath")));
                bean.setStartTime(cursor.getLong(cursor.getColumnIndex("starttime")));
                bean.setEndTime(cursor.getLong(cursor.getColumnIndex("endtime")));
                bean.setNoteClass(cursor.getString(cursor.getColumnIndex("noteclass")));
                exportList.add(bean);
            }
            if (exportList.size() > 0) {
                new exportTask().execute();
            } else {
                handler.sendEmptyMessageDelayed(2, 1000);
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    }

    private void showFCDialog(final int position) {
        final AlertDialog.Builder tipDialog =
                new AlertDialog.Builder(MainActivity.this);
        tipDialog.setTitle("请选择");
        tipDialog.setItems(new String[]{"删除"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DataSupport.delete(NoteBean.class, list.get(position).getId());
                list.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
        tipDialog.show();
    }

    private void searchDept() {
        data = DataSupport.findAll(NoteDeptBean.class);
        NoteDeptBean a = new NoteDeptBean();
        a.setDeptName("全部分组");
        a.setId(-1);
        data.add(0, a);
        NoteDeptBean b = new NoteDeptBean();
        b.setDeptName("默认分组");
        b.setId(0);
        data.add(1, b);
    }

    private void showPopu() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_pop_class_select, null);
        AutoUtils.auto(contentView);
        lvGroup = (ListView) contentView.findViewById(R.id.note_group_list);
        adapterGroup = new GroupListAdapter();
        lvGroup.setAdapter(adapterGroup);
        lvGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dept = data.get(position).getDeptName();
                tvClass.setText(dept);
                searchNote(true);
                pwClass.dismiss();
            }
        });
        pwClass = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        pwClass.setBackgroundDrawable(getResources().getDrawable(R.drawable.pop_background));
        pwClass.showAsDropDown(findViewById(R.id.note_main_title));
    }

    class ViewHodlerNote {
        TextView tvTitle, tvDept, tvTime;
    }

    class NoteListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHodlerNote viewHodler;
            if (convertView == null) {
                viewHodler = new ViewHodlerNote();
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_note, null);
                AutoUtils.auto(convertView);
                viewHodler.tvDept = (TextView) convertView.findViewById(R.id.note_dept);
                viewHodler.tvTitle = (TextView) convertView.findViewById(R.id.note_title);
                viewHodler.tvTime = (TextView) convertView.findViewById(R.id.note_time);
                convertView.setTag(viewHodler);
            } else {
                viewHodler = (ViewHodlerNote) convertView.getTag();
            }
            viewHodler.tvTitle.setText(list.get(position).getTitle());
            viewHodler.tvDept.setText(list.get(position).getNoteClass());
            viewHodler.tvTime.setText(ToolUtils.TS2S(list.get(position).getStartTime(), "yyyy-MM-dd HH:mm"));
            return convertView;
        }
    }

    class ViewHodlerClass {
        TextView tvDept;
    }

    class GroupListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHodlerClass viewHodler;
            if (convertView == null) {
                viewHodler = new ViewHodlerClass();
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_note_group_select, null);
                AutoUtils.auto(convertView);
                viewHodler.tvDept = (TextView) convertView.findViewById(R.id.note_group_tv_name);
                convertView.setTag(viewHodler);
            } else {
                viewHodler = (ViewHodlerClass) convertView.getTag();
            }
            viewHodler.tvDept.setText(data.get(position).getDeptName());
            return convertView;
        }
    }

    class exportTask extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            if (list.size() > 0) {
                String fileName = "";
                if (sDate != 0 && eDate != 0) {
                    fileName = ToolUtils.TS2S(sDate, "yyyy-MM-dd") + "至" + ToolUtils.TS2S(eDate, "yyyy-MM-dd") + "的数据";
                } else if (sDate == 0 && eDate == 0) {
                    fileName = "全部数据";
                } else if (sDate == 0) {
                    fileName = ToolUtils.TS2S(eDate, "yyyy-MM-dd") + "之前的数据";
                } else {
                    fileName = ToolUtils.TS2S(sDate, "yyyy-MM-dd") + "至今的数据";
                }
                return ExcelUtils.writeObjListToExcel(list, fileName, MainActivity.this);
            } else {
                Toast.makeText(MainActivity.this, "暂无可导出数据", Toast.LENGTH_SHORT).show();
                return null;
            }
        }

        @Override
        protected void onPostExecute(Boolean flag) {
            Message msg = new Message();
            if (flag) {
                msg.what = 1;
            } else {
                msg.what = 0;
            }
            handler.sendMessageDelayed(msg, 1000);
            super.onPostExecute(flag);
        }

        @Override
        protected void onPreExecute() {
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            loading.setVisibility(View.GONE);
            if (msg.what == 1) {
                Toast.makeText(MainActivity.this, "导出到" + FileUtils.rootExcelDir + "下", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0) {
                Toast.makeText(MainActivity.this, "导出失败", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 2) {
                Toast.makeText(MainActivity.this, "无可导出的数据", Toast.LENGTH_SHORT).show();
            }
            super.handleMessage(msg);
        }
    };

    public void initFile() {
        File dirFile = new File(FileUtils.rootDir);
        boolean flag = FileUtils.createFolder(dirFile);
        if (flag) {
            Log.e("flag", "目录创建成功呢");
        } else {
            Log.e("flag", "目录创建失败呢");
        }
    }
}
